package com.xja.shoppingmall.util;

import com.alibaba.fastjson.JSON;
import com.xja.shoppingmall.constant.CommonConstant;
import com.xja.shoppingmall.vo.LoginUserInfo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import sun.misc.BASE64Decoder;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Calendar;

/**
 * @author CHENCHEN
 * @title   JWT Token 解析工具
 * @createTime 2021-12-1217:26
 */
public class TokenParseUtil {

    /**
     * 根据本地存储的公钥获取PublicKey对象
     * @return
     * @throws Exception
     */
    private static PublicKey getPublicKey() throws  Exception{
        return KeyFactory
                .getInstance("RSA")
                .generatePublic(
                        new X509EncodedKeySpec(
                                new BASE64Decoder().decodeBuffer(
                                        CommonConstant.PUBLIC_KEY
                                )
                        )
                );
    }

    /**
     * 通过公钥解析token
     * @param token
     * @param publicKey
     * @return
     */
    private static Jws<Claims> parseToken(String token, PublicKey publicKey){
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * 通过解析token获取到 LoginUserInfo对象
     * @param token
     * @return
     * @throws Exception
     */
    public static LoginUserInfo parseUserInfoFromToken(String token) throws Exception{
        if(token == null) {
            return null;
        }
        Claims body = parseToken(token, getPublicKey()).getBody();
        //如果token已经过期了，返回Null
        if(body.getExpiration().before(Calendar.getInstance().getTime())){
            return null;
        }
        //返回 Token 中保存的用户信息
        return JSON.parseObject(
                body.get(CommonConstant.JWT_USER_INFO_KEY).toString(),
                LoginUserInfo.class
        );
    }
}
